<template>
  <el-select
    v-model="selectedSpaceId"
    placeholder="选择限定的空间"
    @visible-change="openSelect"
    @change="handleSelect"
  >
    <el-option-group>
      <el-option label="全平台统计" :value="undefined" class="no-limit-height">
        <div class="flex align-items-center title easy-container-4">
          <svg-icon icon-name="logo" class="s28 m-r-5" />
          全平台统计
        </div>
      </el-option>
    </el-option-group>
    <el-option-group v-loading="loading">
      <el-option
        v-for="space in relatedSpaces"
        :key="space.id"
        :label="space.title"
        :value="space.id"
        class="no-limit-height"
      >
        <div class="flex align-items-center title easy-container-4">
          <el-avatar :src="space.avatar" size="small" class="m-r-5" />
          {{ space.title }}
        </div>
      </el-option>
    </el-option-group>
  </el-select>
</template>

<script>
import { formatRelatedSpaces } from '@/views/groups/format';

export default {
  name: 'select-related-space',
  props: {
    selectedSpace: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      selectedSpaceId: undefined,
      selectedSpaceTitle: undefined,
      relatedSpaces: [],
      loading: false,
    };
  },
  methods: {
    openSelect(open) {
      if (open && !this.relatedSpaces.length) this.loadRelatedSpaces();
    },
    handleSelect(spaceId) {
      const index = this.relatedSpaces.map(s => s.id).indexOf(spaceId);
      this.$emit('update:selectedSpace', (this.relatedSpaces[index] || {}));
    },
    // 获取群组关联的空间
    loadRelatedSpaces() {
      this.loading = true;
      this.$api.groups.relatedSpaces({
        groupId: this.$route.params.groupId,
      }).then((res) => {
        this.relatedSpaces = formatRelatedSpaces(res.data);
      }).catch(() => {})
        .then(() => { this.loading = false; });
    },
  },

};
</script>

<style></style>
